package com.right.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 解决SimpleDateFormat并发错乱问题
 */
public class DateUtil {
    public final static String yyyyMMddHHmmss="yyyy-MM-dd HH:mm:ss";
    public final static String yyyyMMddHHmmss2="yyyyMMddHHmmss";
    public final static String yyyyMMdd="yyyyMMdd";
    public final static String yyyyMMdd2="yyyy-MM-dd";
    public final static String yyMMddHHmmss="yyMMddHHmmss";
    /** 锁对象 */
    private static final Object lockObj = new Object();

    /** 存放不同的日期模板格式的sdf的Map */
    private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new ConcurrentHashMap<>();

    /**
     * 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
     * @param pattern
     * @return
     */
    private static SimpleDateFormat getSdf(final String pattern) {
        ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
        if (tl == null) {
            synchronized (lockObj) {
                // 这里是关键,使用ThreadLocal<SimpleDateFormat>替代原来直接new SimpleDateFormat
                tl = sdfMap.computeIfAbsent(pattern, p -> ThreadLocal.withInitial(() -> new SimpleDateFormat(p)));
            }
        }
        return tl.get();
    }


    public static String format(Date date, String pattern) {
        return getSdf(pattern).format(date);
    }

    public static DateFormat getDateFormat(String pattern){
        return getSdf(pattern);
    }
    public static Date parse(String dateStr, String pattern) throws ParseException {
        return getSdf(pattern).parse(dateStr);
    }

    /**
     * 计算时间差
     * @param startTime
     * @param endTime
     * @return
     */
    public static String getOnLineTime(Date startTime, Date endTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long ns = 1000;
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;

        diff = endTime.getTime() -startTime.getTime();
        day = diff / nd;
        hour = diff % nd / nh + day * 24;
        min = diff % nd % nh / nm + day * 24 * 60;
        sec = diff % nd % nh % nm / ns;
        System.out.println("时间相差：" + day + "天" + (hour - day * 24) + "小时"
                + (min - day * 24 * 60) + "分钟" + sec + "秒。");
        return String.format("本次在线时长:%d天%d时%d分%d秒",day,(hour - day * 24),(min - day * 24 * 60),sec);

    }
}